# coding=utf-8
import json
import os
import random

import datetime
import requests

from db.model import Article
from db.user import User
from settings import duoshuo_name

template_list = ['_personal.md']

def isIgnore(path):
    file_name = os.path.basename(path)
    if file_name.startswith('_'):
        return True
    else:
        return False

def getComments():
    articles = Article.select()
    id_list = []
    for art in articles:
        id_list.append(art.id)
    req = requests.get(url='http://api.duoshuo.com/threads/counts.json', params={
        'short_name': duoshuo_name,
        'threads': ','.join(id_list),
        'v': str(random.random())
    })
    res = json.loads(req.text)

    # with db.transaction() as txn:
    # q = Article.update(comment_count=210).where(Article.id == '0c5087eb23b7a0d6e7607c9645a6e275')
    # q.execute()

    if res['code'] == 0:
        comments = res['response']
        with User.db.transaction() as txn:
            for id, value in comments.iteritems():
                update = Article.update(comment_count=value['comments'],
                                        like_count=value['likes'],
                                        repost_count=value['reposts']).where(Article.id == id)
                update.execute()
            txn.commit()


def buildPathTree(tree, title, path):
    """
        path:/xxx/yyy/zzz/ooo.md
    """
    block = path[1:].split('/')
    this = tree
    for index, li in enumerate(block):
        if li.endswith('.md'):
            text = li[:-3]
            this[title] = {
                'type': 0,
                'a': path[1:-3]
            }
            this = this[title]
        else:
            if li not in this:
                this[li] = {
                    'type': 1,
                    'items': {}
                }
            this = this[li]['items']


def buildTimeTree(tree, date, title, path):
    """
        time:datetime
    """
    year = date.year
    month = date.month
    day = date.day
    list = [year, month, day]
    list_tip = ['年', '月', '日']
    this = tree
    for i, li in enumerate(list):
        if li not in this:
            this[li] = {
                'type': 1,
                'items': {},
                'tip': list_tip[i]
            }
        this = this[li]['items']

    this[title] = {
        'type': 0,
        'a': path[1:-3]
    }
